iT邦幫忙

2022 iThome 鐵人賽

DAY 23
0
Modern Web

clojure 刷刷鍋系列 第 23

Clojure 肉片 -第 23 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

Definition
Strong number is the number that the sum of the factorial of its digits is equal to number itself.

For example, 145 is strong, since 1! + 4! + 5! = 1 + 24 + 120 = 145.

Task
Given a number, Find if it is Strong or not and return either "STRONG!!!!" or "Not Strong !!".

(必須通過以下測試)

(ns kata.test
  (:require [clojure.test :refer :all]
            [kata :refer :all]))
(defn tester [n exp]
  (testing (str "Testing for " n)
    (is (= (strong n) exp))))
(deftest basic-tests
  (tester 1 "STRONG!!!!")
  (tester 2 "STRONG!!!!")
  (tester 145 "STRONG!!!!")
  (tester 40585 "STRONG!!!!")
  (tester 7 "Not Strong !!")
  (tester 93 "Not Strong !!")
  (tester 185 "Not Strong !!"))

【我的答案】

(ns kata)
(defn strong [n]
  (let [is-strong (= n (->> (clojure.string/split (str n) #"")  
                         (map #(Integer/parseInt %))
                         (map #(reduce * (range 1 (inc %))))
                         (reduce +)))]
    (if is-strong "STRONG!!!!" "Not Strong !!"))
)

【其他人的答案】

(ns kata)

(defn fact [n]
  (apply * (range 1 (inc n))))

(defn digits [n]
  (->> (iterate #(quot % 10) n)
       (take-while pos?)
       (map #(rem % 10))))

(defn digits-fact-sum [n]
  (->> (digits n)
       (map fact)
       (apply +)))

(defn strong [n]
  (if (= n (digits-fact-sum n))
    "STRONG!!!!"
    "Not Strong !!"))
(ns kata)
(defn digits [n] (map #(Character/digit % 10) (str n)))
(defn factorial [n] (reduce * (range 1 (inc n))))
(defn strong [n]
  (if (= n (reduce + (map #(factorial %) (digits n))))
    "STRONG!!!!"
    "Not Strong !!"))
(ns kata)
(defn strong [n]
  (if (.contains [1 2 145 40585] n) "STRONG!!!!" "Not Strong !!"))

上一篇
Clojure 肉片 -第 22 塊(的一半)
下一篇
Clojure 肉片 -第 24 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言